import axios from 'axios'
import { Notification, Message } from "element-ui"
import * as auth from '../utils/auth'
import { removeToken, getToken } from '@/utils/auth'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'


// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_URL,
    // 超时
    timeout: 60000,
    withCredentials: true,
    crossDomain: true
})

let errorcount = 0
let errorcountlist = []
let timer = null;

let interfaceParams = {
    environmentId:1,
    method:'',
    serviceId:13,
    systemId:3,
    url:'',
}

function interfaceLog(params){
    axios.post(process.env.NODE_ENV == 'development' ? process.env.VUE_APP_MONITOR +'api/v1/interfaceCallLog/save':  process.env.VUE_APP_MONITOR +'api/v1/interfaceCallLog/save',params).then(res=>{
        return res.data
    })
}

//请求拦截，在每个请求发出去之前，针对每个域名做不同的配置
service.interceptors.request.use((config) => {
    config.baseURL = process.env.VUE_APP_BASE_URL;
    if(config.requestBaseUrl == 'log'){
        config.baseURL = process.env.VUE_APP_MONITOR;
    }
    if (config.requestBaseUrl == "outside") {
        config.baseURL = process.env.VUE_APP_BASE_DATA_URL;
    }
    let site = config.baseURL.split('/')[2];
    if(site == 'out.bj.51db.com:36101'){
        interfaceParams.environmentId = 1
    }else if(site == 'out.bj.51db.com:36201'){
        interfaceParams.environmentId = 2
    }else if(site == 'srm.b1b.cn:36301'){
        interfaceParams.environmentId = 4
    }
    // console.log(site,'sitesite');
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    let Token = auth.getToken();
    
    if (Token && !isToken) {
        config.headers["Token"] = "Bearer " + auth.getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Authorization'] = '6a77998089b8467d83d2094a8011b02d'
    interfaceParams.method = config.method;
    interfaceParams.url = config.url;
    interfaceLog(interfaceParams) // 暂时注释接口
    return config
})

// 响应拦截器
service.interceptors.response.use(
    (res) => {
            // 未设置状态码则默认成功状态
        const code = res.data.status || 200
        if (code === 500) {
            const msg = res.data.data
            Message({
                message: msg,
                type: "error",
                offset: window.screen.height / 3,
            })
            return Promise.reject(msg)
        } else if (code !== 200) {
            Notification.error({
                title: msg,
            })
            return Promise.reject("error")
        } else {
            let arr = [3003,3009,3010,3011,3012,3013,3014]
            if(arr.findIndex(item => item === res.data.code )!==-1){
                removeToken()
                console.log(getToken(), 'dddddgetToken')
                if (getToken() == undefined) {
                    location.href = '#/login'
                } 
            }else{
                return res.data;
            }  
        }
    },
    (error) => {
        let code = (error.response && error.response.status) || ""
            console.log(code, 'code')
        if (code === 401) {
            Message({
                message: (error.response && error.response.data) ? error.response.data.message : '发生错误:' + code + ',请重试',
                type: 'error',
                duration: 3 * 1000,
                offset: window.screen.height / 3,
            })
            let arr = [3003,3009,3010,3011,3012,3013,3014]
            if(arr.findIndex(item => item === error.response.data.code )!==-1){
                removeToken()
                if (getToken() == undefined) {
                    location.href = '#/login'
                } 
            } 
        } else if(code == 503){
            Message({
                message: '服务忙，请稍后重试',
                type: "error",
                offset: window.screen.height / 3,
            })
        }else{
            if (!errorcountlist.includes(code) && code) {
                Message({
                    message: (error.response && error.response.data) ? error.response.data.message : '发生错误:' + code + ',请重试',
                    type: 'error',
                    duration: 3 * 1000,
                    offset: window.screen.height / 3
                })
                errorcountlist.push(code)
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                errorcountlist = []
            }, 2500)
            return Promise.reject(error)
        }
    }
)


export default service